<?php
/* 1. is_phish()
-------------
Imagine that you run a very popular URL shortening service (similar to
bit.ly, is.gd, etc.), and want to prevent malicious users from masking
phishing sites with your service. One way you might do this is to check
submitted URLs against the PhishTank Web site to see if it considers
them to be phishes. Using the information at
http://www.phishtank.com/developer_info.php, implement a PHP function
called is_phish() that performs this check. Your function should have
the signature "bool is_phish(string $url)". Because your service is so
popular, it sees over 50 new URLs per second, so keep that in mind when
interacting with PhishTank.
*/

class Phishy 
{
    protected $lookupPhishURLs = "http://data.phishtank.com/data/76462a7bc4d8f644f4c71210bf7581754c676ec30cd78ba6f5828cfdcad51ec0/online-valid.xml";
    
    /*
     * get HTTP last-modified header information
     * returns remote time of the retrieved document
     */
    private function getFiletime($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_FILETIME, true);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_exec($curl);
        $info = curl_getinfo($curl);
        curl_close($curl);
        return $info['filetime'];
    }
        
    /*
     * cache remote XML file to a local file
     * or update local file if remote XML file has been updated 
     * since the timestamp limit.  returns SimpleXMLElement object
    */
    private function get_xml($url, $max_age) 
    {
        $file = dirname(__FILE__) . '/cacheDB.xml';
        $phishTime = $this->getFiletime($url);
        
        if ($phishTime < time() - $max_age)
        {
            // the cache file doesn't exists or is not fresh enough
            if (!file_exists($file) 
                || filemtime($file) < time() - $max_age)
                    copy($url, $file);
        }
        return simplexml_load_file($file, 'SimpleXMLElement', LIBXML_NOCDATA);
    }
    
    public function is_phish($url)
    {
        //set max_time to check HTTP header information to 20 minutes
        //since PhishTank updates every hour on the hour.
        $xml =  $this->get_xml($this->lookupPhishURLs, 1200);
        if ($xml === FALSE) {  exit("Unable to retrieve PhishTank data lookup");  }
        
        return in_array($url, $xml->xpath('//url'));
    }
    
    public function testIs_Phish($url)
    {
        if ($this->is_phish($url)) {
            echo $url . ' LOOKS PHISHY TO ME.<br/>';
        } else {
            echo $url . ' IS GOOD TO GO. <br/>';
        }
    }
}

//$phish = new Phishy;
//echo $phish->testIs_Phish("http://google.com");
//echo $phish->testIs_Phish("http://www.acleth.ca/www.diners.com.br/Cadastra.php?Local=SMS+Email&IdPromo=01");


?>